# Verify conditions
if [ ! -z $UID ] && [ $UID -ne 0 ]; then
    echo Superuser privileges are required to run this script.
    exit 1
fi

ping -c 1 -W 1 8.8.8.8 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    ping -c 1 -W 1 www.baidu.com > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo Network unreachable.
        exit 1
    fi
fi

# Remove files of legacy installation
if [ -d "/opt/dotnet" ]; then
    rm -rf /opt/dotnet
    echo /opt/dotnet removed.
fi

if [ ! -z `cat /etc/environment | grep DOTNET_ROOT=` ]; then
    sed -i '/^DOTNET_ROOT=/d' /etc/environment
    echo /etc/environment reverted.
fi

if [ -f "/etc/profile.d/dotnet-core.sh" ]; then
    rm -f /etc/profile.d/dotnet-core.sh
    echo /etc/profile.d/dotnet-core.sh removed.
fi

if [ -f "/etc/profile.d/dotnet.sh" ]; then
    rm -f /etc/profile.d/dotnet.sh
    echo /etc/profile.d/dotnet.sh removed.
fi

if [ -f "/etc/profile.d/dotnet-manually-installed.sh" ]; then
    rm -f /etc/profile.d/dotnet-manually-installed.sh
    echo /etc/profile.d/dotnet-manually-installed.sh removed.
fi

if [ -d "/usr/share/dotnet-manually-installed" ]; then
    rm -rf /usr/share/dotnet-manually-installed
    echo /usr/share/dotnet-manually-installed removed.
fi

# Remove install lock
if [ -f "/var/lib/apt/lists/lock" ] || [ -f "/var/lib/dpkg/lock" ] || [ -f "/var/lib/dpkg/lock-frontend" ] || [ -f "/var/cache/apt/archives/lock" ]; then
    echo The apt system may be locked. Trying to unlock.
    apt update
    rm -f /var/lib/apt/lists/lock
    rm -f /var/lib/dpkg/lock
    rm -f /var/lib/dpkg/lock-frontend
    rm -f /var/cache/apt/archives/lock
fi

# Add Microsoft source
mkdir -p /tmp
wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb
dpkg -i /tmp/packages-microsoft-prod.deb
rm /tmp/packages-microsoft-prod.deb

mkdir -p /etc/apt/preferences.d
echo $'Package: *\nPin: origin \"packages.microsoft.com\"\nPin-Priority: 1001' > /etc/apt/preferences.d/99microsoft-dotnet.pref

# Update apt
apt update

# Install .net
apt install -y dotnet-runtime-8.0=8.0.11-1
apt install -y dotnet-runtime-3.1

apt-mark hold dotnet-host
apt-mark hold dotnet-hostfxr-8.0
apt-mark hold dotnet-runtime-8.0
apt-mark hold dotnet-runtime-deps-8.0
apt-mark hold dotnet-targeting-pack-8.0

if [ ! -f "/etc/environment.d/dotnet-asc.conf" ]; then
    mkdir -p /etc/environment.d
    echo 'COMPlus_EnableAlternateStackCheck=1' > /etc/environment.d/dotnet-asc.conf
fi

# Install other software
apt install -y libsqlite3-0 libwebkit2gtk-4.0-37 libpython3-dev python3-pip mesa-utils mesa-va-drivers i965-va-driver intel-media-va-driver-non-free vdpau-driver-all libmfx1 intel-opencl-icd

# Install OpenCV
OPENCV_PACKAGE=OpenCV410-X86Ubuntu2204.zip
if [ -f $OPENCV_PACKAGE ]; then
    apt install -y libopenexr25 libdc1394-25 ffmpeg libtesseract4 libogre1.12.10 libgoogle-glog0v5 nvidia-cuda-toolkit nvidia-cudnn libvtk9.1 qtbase5-dev
    unzip -o -d / ./$OPENCV_PACKAGE
fi

echo Done.
